package com.frxuexi.lib_base

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch

abstract class BaseViewModel<UiIntent:IUiIntent>:ViewModel() {
    val channel = Channel<UiIntent>()

    private var _state= MutableStateFlow<UiState>(UiState.onLoading)
    val state:StateFlow<UiState>
        get() = _state

    init {
        viewModelScope.launch {
            channel.receiveAsFlow().collect{
                handleIntent(it)
            }
        }
    }

    /**
     * 处理意图
     */
    abstract fun handleIntent(it: UiIntent)

    /**
     * 发送意图
     */
    fun sendIntent(intent: UiIntent){
        viewModelScope.launch {
            channel.send(intent)
        }
    }

    /**
     * 网络请求
     */
    fun httpRequest(request:Flow<ApiResp<Any>>){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    if(it.statusCode==200){
                        _state.value=UiState.onSuccess(it.data)
                    }else{
                        _state.value=UiState.onError(it.msg!!)
                    }
                }
        }
    }
}